import type {AxiosInstance, AxiosResponse} from "axios";

import { ElMessage } from "element-plus";

import { useStore } from "@/stores";

import { useRouter } from "vue-router";

export const configureInterceptors = (instance : AxiosInstance) => {
    instance.interceptors.request.use((config) => {
        const token = useStore().user.token;

        if(token !== null && token.trim() !== '') {
            config.headers['Authorization'] = token;
        }

        return config;
    });

    instance.interceptors.response.use((response: AxiosResponse) => {
        const { config, data } = response as AxiosResponse<JsonResult>;

        if("/v1/user/myInfo" === String(config.baseURL) + String(config.url)) {
            return response;
        }

        if(data.code === StatusCode.NOT_LOGIN) {
            useRouter().push('/login');
            useStore().user.logout();
            ElMessage.warning('您未登录, 请先登录');
        }

        return response;
    }, (err) => {
        ElMessage.error('服务暂不可用');
        console.log(err);

        return Promise.reject(err);
    });
};

export const enum StatusCode {
    SUCCESS = 2000, LOGIN_SUCCESS, OPERATION_SUCCESS,
    NOT_LOGIN = 4000, LOGIN_EXPIRED, PASSWORD_ERROR, AUTHORITY_ERROR,
    OPERATION_FAILED = 5001, VALIDATE_ERROR, USERNAME_ALREADY_EXISTS, DATA_UNEXISTS
}

export interface JsonResult<T = any> {
    code: StatusCode | number,
    msg: string,
    data: T
}
